package com.qyhl.school.school.home;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qinanyu.bannerview.holder.SimpleHolder;
import com.qinanyu.bannerview.holder.SimpleHolderCreator;
import com.qinanyu.bannerview.listener.OnItemClickListener;
import com.qinanyu.bannerview.view.SimpleBannerView;
import com.qyhl.school.R;
import com.qyhl.school.R2;
import com.qyhl.school.school.SchoolHomeActivity;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.live.TeleTextBean;
import com.qyhl.webtv.commonlib.entity.news.NewsBean;
import com.qyhl.webtv.commonlib.entity.school.SchoolListBean;
import com.qyhl.webtv.commonlib.entity.school.SchoolMainBean;
import com.qyhl.webtv.commonlib.entity.school.SchoolVlogBean;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.gridviewpager.GridViewPager;
import com.qyhl.webtv.commonlib.utils.view.gridviewpager.GridViewPagerDataAdapter;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class SchoolMainFragment extends BaseFragment implements SchoolMainContract.SchoolMainView {
    @BindView(R2.id.banner)
    SimpleBannerView banner;
    @BindView(R2.id.highlight_more)
    TextView highlightMore;
    @BindView(R2.id.highlight_recycler)
    RecyclerView highlightRecycler;
    @BindView(R2.id.highlight_layout)
    RelativeLayout highlightLayout;
    @BindView(R2.id.school_more)
    TextView schoolMore;
    @BindView(R2.id.school_navigation)
    GridViewPager schoolNavigation;
    @BindView(R2.id.reporter_more)
    TextView reporterMore;
    @BindView(R2.id.reporter_cover)
    RoundedImageView reporterCover;
    @BindView(R2.id.reporter_title)
    TextView reporterTitle;
    @BindView(R2.id.reporter_address)
    TextView reporterAddress;
    @BindView(R2.id.reporter_date)
    TextView reporterDate;
    @BindView(R2.id.reporter_layout)
    RelativeLayout reporterLayout;
    @BindView(R2.id.vlog_more)
    TextView vlogMore;
    @BindView(R2.id.vlog_recycler)
    RecyclerView vlogRecycler;
    @BindView(R2.id.vlog_layout)
    RelativeLayout vlogLayout;
    @BindView(R2.id.live_more)
    TextView liveMore;
    @BindView(R2.id.live_recycler)
    RecyclerView liveRecycler;
    @BindView(R2.id.live_layout)
    RelativeLayout liveLayout;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.school_layout)
    CardView schoolLayout;
    @BindView(R2.id.point_layout)
    LinearLayout mPointLayout;
    /**
     * 数据是否第一次加载
     */
    private boolean mIsInited;
    /**
     * 布局界面初始化
     */
    private boolean mIsPrepared;

    private SchoolMainPresenter mPresenter;

    private SchoolMainBean mBean;

    private CommonAdapter<NewsBean> highlightCommonAdapter;
    private List<NewsBean> highlightList = new ArrayList<>();

    private List<SchoolListBean> schoolList = new ArrayList<>();

    private CommonAdapter<SchoolVlogBean> vlogCommonAdapter;
    private List<SchoolVlogBean> vlogList = new ArrayList<>();

    private CommonAdapter<TeleTextBean> liveCommonAdapter;
    private List<TeleTextBean> liveList = new ArrayList<>();

    private List<NewsBean> bannerList = new ArrayList<>();

    private ImageView[] imgs;//动态创建滑动指示器

    private static final int COLUMNS_NUM = 4;//导航栏列数
    private static final int ROWS_NUM = 2;//导航栏行数

    public static SchoolMainFragment newInstance() {
        SchoolMainFragment fragment = new SchoolMainFragment();
        return fragment;
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_school_main, null);
    }

    @Override
    protected void create() {
        loadMask.setStatus(LoadingLayout.Loading);

        mPresenter = new SchoolMainPresenter(this);

        refresh.setRefreshHeader(new MaterialHeader(getContext()));
        refresh.setEnableLoadMore(false);

        highlightRecycler.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        highlightRecycler.setAdapter(highlightCommonAdapter = new CommonAdapter<NewsBean>(getContext(), R.layout.item_school_main_highlight, highlightList) {
            @Override
            protected void convert(ViewHolder viewHolder, NewsBean newsBean, int i) {
                RoundedImageView cover = viewHolder.getView(R.id.cover);
                Glide.with(SchoolMainFragment.this)
                        .load(newsBean.getLogo())
                        .apply(new RequestOptions().error(R.drawable.cover_large_default).placeholder(R.drawable.cover_large_default))
                        .into(cover);

                viewHolder.setText(R.id.title, newsBean.getTitle());
            }
        });


        vlogRecycler.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        vlogRecycler.setAdapter(vlogCommonAdapter = new CommonAdapter<SchoolVlogBean>(getContext(), R.layout.item_school_main_vlog, vlogList) {
            @Override
            protected void convert(ViewHolder viewHolder, SchoolVlogBean schoolVlogBean, int i) {
                RoundedImageView cover = viewHolder.getView(R.id.cover);
                Glide.with(SchoolMainFragment.this)
                        .load(schoolVlogBean.getLogo())
                        .apply(new RequestOptions().error(R.drawable.cover_large_default).placeholder(R.drawable.cover_large_default))
                        .into(cover);

                viewHolder.setText(R.id.title, schoolVlogBean.getInfo());
            }
        });

        liveRecycler.setLayoutManager(new LinearLayoutManager(getContext()));
        liveRecycler.setAdapter(liveCommonAdapter = new CommonAdapter<TeleTextBean>(getContext(), R.layout.item_school_main_live, liveList) {
            @Override
            protected void convert(ViewHolder viewHolder, TeleTextBean teleTextBean, int i) {
                RoundedImageView cover = viewHolder.getView(R.id.cover);
                Glide.with(SchoolMainFragment.this)
                        .load(teleTextBean.getCoverPic())
                        .apply(new RequestOptions().error(R.drawable.cover_large_default).placeholder(R.drawable.cover_large_default))
                        .into(cover);

                viewHolder.setText(R.id.title, teleTextBean.getTitle());

                switch (teleTextBean.getStatus()) {
                    case "2":
                        viewHolder.setVisible(R.id.live_tag, true);
                        viewHolder.setImageResource(R.id.live_tag, R.drawable.school_live_tag_live);
                        break;
                    case "6":
                        viewHolder.setVisible(R.id.live_tag, true);
                        viewHolder.setImageResource(R.id.live_tag, R.drawable.school_live_tag_forecast);
                        break;
                    default:
                        viewHolder.setVisible(R.id.live_tag, false);
                        break;
                }
            }
        });

        mPresenter.getData();
    }

    @Override
    protected void setListener() {
        //导航栏滑动监听
        schoolNavigation.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                setIndicator(position);//设置滑动指示器
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View view) {
                loadMask.setReloadButtonText("加载中...");
                mPresenter.getData();
            }
        });

        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getData();
            }
        });

        banner.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                newsSkip(bannerList.get(position));
            }
        });

        highlightCommonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                newsSkip(highlightList.get(i));
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                return false;
            }
        });

        vlogCommonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("bean", (Serializable) vlogList);
                ARouter.getInstance().build(ARouterPathConstant.SCHOOL_VLOG_PLAY)
                        .withBundle("list", bundle)
                        .withInt("position", i)
                        .withInt("type", 1)
                        .navigation();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                return false;
            }
        });

        liveCommonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                ARouter.getInstance().build(ARouterPathConstant.TELE_VIDEO_ACTIVITY)
                        .withString("id", mBean.getLiveList().get(i).getId() + "")
                        .navigation();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                return false;
            }
        });
    }

    @Override
    protected void onFirstVisible() {

    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }

    //设置滑动指示器
    private void setIndicator(int position) {
        for (int i = 0; i < imgs.length; i++) {
            if (i == position) {
                imgs[i].setImageResource(R.drawable.school_navigation_indicator_on);
            } else {
                imgs[i].setImageResource(R.drawable.school_navigation_indicator_off);
            }
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void setData(SchoolMainBean bean) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        refresh.finishRefresh();

        mBean = bean;

        if (mBean.getCarousel() != null && mBean.getCarousel().size() > 0) {
            banner.setVisibility(View.VISIBLE);
            bannerList.clear();
            bannerList.addAll(mBean.getCarousel());

            List<String> titleNames = new ArrayList<>();
            for (int i = 0; i < bannerList.size(); i++) {
                titleNames.add(bannerList.get(i).getTitle());
            }
            String[] titleStrings = new String[titleNames.size()];
            titleNames.toArray(titleStrings);
            //当只有一张轮播图时
            if (bannerList.size() == 1) {
                banner.setTextBanner(titleStrings[0]);
                banner.setCanLoop(false);//停止轮播
            }

            banner.setPages(new SimpleHolderCreator() {
                @Override
                public Object createHolder() {
                    return new BannerImageHolderView();
                }
            }, bannerList)
                    .startTurning(3000)//轮播3s一次
                    .setPageIndicator(new int[]{R.drawable.banner_indicator_off, R.drawable.school_banner_indicator_on}, titleStrings)
                    .setPageIndicatorAlign(SimpleBannerView.PageIndicatorAlign.ALIGN_PARENT_RIGHT);
        } else {
            banner.setVisibility(View.GONE);
        }

        //精彩看点
        if (mBean.getHighLightList() != null && mBean.getHighLightList().size() > 0) {
            highlightMore.setVisibility(View.VISIBLE);
            highlightLayout.setVisibility(View.VISIBLE);

            highlightList.clear();
            highlightList.addAll(mBean.getHighLightList());
            highlightCommonAdapter.notifyDataSetChanged();
        } else {
            highlightMore.setVisibility(View.GONE);
            highlightLayout.setVisibility(View.GONE);
        }

        //小记者团
        if (mBean.getReportActivity() != null && mBean.getReportActivity().getId() != 0) {
            reporterLayout.setVisibility(View.VISIBLE);
            reporterMore.setVisibility(View.VISIBLE);

            reporterTitle.setText(mBean.getReportActivity().getTitle());
            reporterAddress.setText(mBean.getReportActivity().getAddress());
            if (StringUtils.isNotEmpty(mBean.getReportActivity().getEndDate())) {
                reporterDate.setText(mBean.getReportActivity().getStartDate() + "—" + mBean.getReportActivity().getEndDate());
            } else {
                reporterDate.setText(mBean.getReportActivity().getStartDate());
            }

            Glide.with(SchoolMainFragment.this)
                    .load(mBean.getReportActivity().getLogo())
                    .apply(new RequestOptions().error(R.drawable.cover_large_default).placeholder(R.drawable.cover_large_default))
                    .into(reporterCover);

        } else {
            reporterLayout.setVisibility(View.GONE);
            reporterMore.setVisibility(View.GONE);
        }

        //学校
        if (mBean.getSchoolList() != null && mBean.getSchoolList().size() > 0) {
            schoolLayout.setVisibility(View.VISIBLE);
            schoolMore.setVisibility(View.VISIBLE);
            mPointLayout.setVisibility(View.VISIBLE);

            schoolList = mBean.getSchoolList();
            schoolNavigation.setGridViewPagerDataAdapter(new GridViewPagerDataAdapter<SchoolListBean>(schoolList, ROWS_NUM, COLUMNS_NUM) {
                @Override
                public BaseAdapter getGridViewAdapter(List<SchoolListBean> currentList, int pageIndex) {
                    return new SchoolGridViewAdapter(getContext(), currentList);
                }

                @Override
                public void onItemClick(AdapterView parent, View view, int position, long id, int pageIndex) {
                    int mPosition = pageIndex * COLUMNS_NUM * ROWS_NUM + position;
                    SchoolListBean bean = schoolList.get(mPosition);
                    ARouter.getInstance().build(ARouterPathConstant.SCHOOL_COLUMN_DETAIL)
                            .withInt("schoolId", bean.getId())
                            .navigation();
                }
            });

            mPointLayout.removeAllViewsInLayout();


            imgs = new ImageView[schoolNavigation.getPageCount()];
            if (imgs.length < 2) {
                mPointLayout.setVisibility(View.GONE);
            } else {
                for (int i = 0; i < schoolNavigation.getPageCount(); i++) {
                    imgs[i] = new ImageView(getActivity());
                    if (i == 0) {
                        imgs[i].setImageResource(R.drawable.school_navigation_indicator_on);
                    } else {
                        imgs[i].setImageResource(R.drawable.school_navigation_indicator_off);
                    }
                    imgs[i].setPadding(2, 0, 2, 0);
                    mPointLayout.addView(imgs[i]);
                }
            }
        } else {
            schoolLayout.setVisibility(View.GONE);
            schoolMore.setVisibility(View.GONE);
            mPointLayout.setVisibility(View.GONE);
        }

        //vlog
        if (mBean.getVlogList() != null && mBean.getVlogList().

                size() > 0) {
            vlogLayout.setVisibility(View.VISIBLE);
            vlogMore.setVisibility(View.VISIBLE);

            vlogList.clear();
            vlogList.addAll(mBean.getVlogList());
            vlogCommonAdapter.notifyDataSetChanged();
        } else {
            vlogLayout.setVisibility(View.GONE);
            vlogMore.setVisibility(View.GONE);
        }

        //直播
        if (mBean.getLiveList() != null && mBean.getLiveList().

                size() > 0) {
            liveMore.setVisibility(View.VISIBLE);
            liveLayout.setVisibility(View.VISIBLE);

            liveList.clear();
            liveList.addAll(mBean.getLiveList());
            liveCommonAdapter.notifyDataSetChanged();
        } else {
            liveMore.setVisibility(View.GONE);
            liveLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void setError(String msg) {
        loadMask.setReloadButtonText("点击重试~");
        loadMask.setStatus(LoadingLayout.Error);
        refresh.finishRefresh();
        if (!NetUtil.isNetworkAvalible(getContext())) {
            loadMask.setErrorImage(R.drawable.error_network);
            loadMask.setErrorText("网络异常，请检查您的网络！");
        } else if (msg.contains("暂无")) {
            loadMask.setErrorImage(R.drawable.empty_content);
            loadMask.setErrorText(msg);
        } else {
            loadMask.setErrorImage(R.drawable.error_content);
            loadMask.setErrorText(msg);
        }
    }

    @Override
    public void signResult(boolean isSuccess, String msg) {

    }


    @OnClick({R2.id.reporter_cover, R2.id.back_btn, R2.id.search_bar, R2.id.highlight_more, R2.id.school_more, R2.id.reporter_more, R2.id.vlog_more, R2.id.live_more})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.reporter_cover) {
            ARouter.getInstance().build(ARouterPathConstant.SCHOOL_REPORTER_ACT_DETAIL)
                    .withInt("actId", mBean.getReportActivity().getId())
                    .navigation();
        } else if (id == R.id.back_btn) {
            if (getActivity() instanceof SchoolHomeActivity) {
                ((SchoolHomeActivity) getActivity()).doFinish();
            }
        } else if (id == R.id.search_bar) {
        } else if (id == R.id.highlight_more) {
            ARouter.getInstance().build(ARouterPathConstant.NEWS_LIST)
                    .withString("title", "精彩看点")
                    .withString("id", mBean.getJckdCatalogId() + "")
                    .navigation();
        } else if (id == R.id.school_more) {
            if (getActivity() instanceof SchoolHomeActivity) {
                ((SchoolHomeActivity) getActivity()).showMoreSchool();
            }
        } else if (id == R.id.reporter_more) {
            RouterManager.router(ARouterPathConstant.SCHOOL_REPORTER_ACT_LIST);
        } else if (id == R.id.vlog_more) {
            RouterManager.router(ARouterPathConstant.SCHOOL_VLOG);
        } else if (id == R.id.live_more) {
            ARouter.getInstance().build(ARouterPathConstant.TELETEXT_LIST)
                    .withString("type", "4")
                    .withString("title", "校园直播")
                    .navigation();
        }
    }


    /**
     * 顶部轮播holder
     */
    static class BannerImageHolderView implements SimpleHolder<NewsBean> {
        private ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, NewsBean data) {
            Glide.with(context.getApplicationContext())
                    .load(data.getLogo())
                    .apply(new RequestOptions().placeholder(R.drawable.cover_large_default).error(R.drawable.cover_large_default))
                    .into(imageView);
        }

    }

    private void newsSkip(NewsBean bean) {
        switch (bean.getType()) {
            case "1"://普通新闻
            {
                Bundle bundle = new Bundle();
                bundle.putString("id", bean.getID());
                RouterManager.router(ARouterPathConstant.NORMAL_NEWS_ACTIVITY, bundle);
            }
            break;
            case "2"://图片新闻
            {
                Bundle bundle = new Bundle();
                bundle.putString("id", bean.getID());
                bundle.putString("section", bean.getCatalogID());
                RouterManager.router(ARouterPathConstant.PICTURE_NEWS_ACTIVITY, bundle);
            }

            break;
            case "3"://直播
            {
                Bundle bundle = new Bundle();
                bundle.putString("newsId", bean.getID());
                bundle.putString("liveType", bean.getLivetype());
                RouterManager.router(ARouterPathConstant.LIVE_NORMAL_ACTIVITY, bundle);
            }
            break;
            case "4"://标题新闻
            {
                Bundle bundle = new Bundle();
                bundle.putString("id", bean.getID());
                bundle.putString("title", bean.getTitle());
                bundle.putString("url", bean.getRedirectURL());
                RouterManager.router(ARouterPathConstant.ADV, bundle);
            }
            break;
            case "5"://视频新闻
            {
                Bundle bundle = new Bundle();
                bundle.putString("id", bean.getID());
                RouterManager.router(ARouterPathConstant.VIDEO_NEWS_ACTIVITY, bundle);
            }
            break;
            case "8"://互动直播
                break;
            case "101"://抓取新闻
            {
                Bundle bundle = new Bundle();
                bundle.putString("id", bean.getID());
                RouterManager.router(ARouterPathConstant.NEWS_CATCH, bundle);
            }
            break;
            default:
                break;

        }
    }

}
